//
//  WD_HomeDetailViewController.m
//  BUDING
//
//  Created by HanWoonYong on 16/4/5.
//  Copyright © 2016年 HanWoonYong. All rights reserved.
//

#import "WD_HomeDetailViewController.h"
#import "WD_MyPlayer.h"
#import "WD_HomeDetailUserCell.h"
#import "WD_HomeDetailTopicCell.h"
#import "WD_HomeDetailMessageCell.h"
#import "WD_HomeDetailDownLoadCell.h"
#import "WD_HomeMessageDetailCell.h"
#import "WD_MovieModel.h"
#import "WD_MovieUrlModel.h"
#import "WD_MovieUserModel.h"
#import "WD_BulletManager.h"
#import "WD_BulletView.h"
#import "WD_BulletModel.h"

@interface WD_HomeDetailViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) WD_MyPlayer *play;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *sectionArr;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, copy)NSString *url;
@property (nonatomic, copy)NSString *viviUrl;
@property (nonatomic, copy)NSString *videoId;
@property (nonatomic, copy)NSString *vedioName;
@property (nonatomic, strong)NSMutableArray *bulletSource;
@property (nonatomic, strong)NSMutableArray *strNameArray;
@property (nonatomic, strong)WD_MovieModel *movieModel;
@property (nonatomic, strong)WD_BulletManager *bullerManager;
@end

@implementation WD_HomeDetailViewController

- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor grayColor];
    [self showView];
    [self getInfo];
    [self BulletData];
}


- (void)showView {
    self.sectionArr = @[@"1", @"2", @"3", @"吐槽"];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT + 100) style:UITableViewStylePlain];
    self.tableView.contentInset = UIEdgeInsetsMake(280, 0, 0, 0);
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[WD_HomeDetailMessageCell class] forCellReuseIdentifier:@"message"];
    [self.tableView registerClass:[WD_HomeDetailDownLoadCell class] forCellReuseIdentifier:@"down"];
    [self.tableView registerClass:[WD_HomeDetailUserCell class] forCellReuseIdentifier:@"user"];
    [self.tableView registerClass:[WD_HomeDetailTopicCell class] forCellReuseIdentifier:@"topic"];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.tableView registerClass:[WD_HomeMessageDetailCell class] forCellReuseIdentifier:@"messageDetail"];
    [self.view addSubview:self.tableView];
    
}

- (void)getInfo {
    [JQAFNetTool GETNetWithUrl:[NSString stringWithFormat:@"http://pudding.cc/api/v1/ep/%@?apiKey=yuki_android&deviceKey=ffffffff-aecb-dcd6-ffff-ffffeb6b6ed7&version=2.8.9&brand=samsung&model=SM-G906S&osv=4.4.2&os=Android&cpuArch=armv7l&timestamp=1459933943&channelId=Wandoujia&auth1=901dbf39b782131ae775446085edf03a", self.idStr] body:nil headerFile:nil response:JQJSON success:^(id result) {
        self.dataSource = [NSMutableArray arrayWithCapacity:0];
        if (result) {
            NSDictionary *dic = result;
            self.movieModel = [[WD_MovieModel alloc] initWithDataSource:dic];
            self.videoId = [self.movieModel.videos[0] objectForKey:@"_id"];
            [self getVideosUrl];
            [self getVividData];
        }
        
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        
        
    }];
    
}

// 标清
- (void)getVideosUrl {
    
    [JQAFNetTool GETNetWithUrl:[NSString stringWithFormat:@"http://x.pudding.cc/api/v1/video/%@/download_info?deviceType=1003&apiKey=yuki_android&os=Android&cpuArch=armv7l&timestamp=1459933483&channelId=Wandoujia&auth1=377b8c022fcc042f84f394ded429cea2", self.videoId] body:nil headerFile:nil response:JQJSON success:^(id result) {
        if (result) {
            NSDictionary *dic = result;
            WD_MovieUrlModel *urlModel = [[WD_MovieUrlModel alloc] initWithDataSource:dic];
            self.url = [NSString stringWithString:[urlModel.sections[0] objectForKey:@"videoUrl"]];
            
        }
        
    } failure:^(NSError *error) {
        
    }];
    
    
}

//高清
- (void)getVividData {
    [JQAFNetTool GETNetWithUrl:[NSString stringWithFormat:@"http://x.pudding.cc/api/v1/video/%@/play_info/?sectionNumber=0&quality=3&deviceType=1003&apiKey=yuki_android&deviceKey=ffffffff-aecb-dcd6-ffff-ffffeb6b6ed7&version=2.8.9&brand=samsung&model=SM-G906S&osv=4.4.2&os=Android&cpuArch=armv7l&timestamp=1459340718&channelId=Wandoujia&auth1=1c640d249205ce03aad1ea3cb732fee9", self.videoId] body:nil headerFile:nil response:JQJSON success:^(id result) {
        if (result) {
            NSDictionary *dic = result;
            WD_MovieUrlModel *urlModel = [[WD_MovieUrlModel alloc] initWithDataSource:dic];
            self.viviUrl = [NSString stringWithString:[urlModel.sections[0] objectForKey:@"videoUrl"]];
            //    播放视频
            _play = [[WD_MyPlayer alloc] initWithMyPlayFrame:CGRectMake(0, 0, WIDTH, 300)];
            _play.url = _viviUrl;
            NSLog(@">>>>>>>>  %@  <<<<<<", _viviUrl);
            UIButton *changeBut = [UIButton buttonWithType:UIButtonTypeSystem];
            changeBut.frame = CGRectMake(200, 20, 40, 20);
            [changeBut setTitle:@"高清" forState:UIControlStateNormal];
            [changeBut addTarget:self action:@selector(changeUrlButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            UIButton *bulletBut = [UIButton buttonWithType:UIButtonTypeSystem];
            bulletBut.frame = CGRectMake(250, 20, 40, 20);
            [bulletBut setTitle:@"弹幕" forState:UIControlStateNormal];
            [bulletBut addTarget:self action:@selector(bulletButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            __weak WD_HomeDetailViewController *myVC = self;
            _play.bigBlock = ^{
                [myVC bigBlock];
            };
            _play.smallBlock = ^{
                [myVC smallBlock];
            };
            _play.backBlock = ^{
                [myVC backBlock];
            };
            [_play.maskView.topImageView addSubview:bulletBut];
            [_play.maskView.topImageView addSubview:changeBut];
            [self.view addSubview:_play];
            
        }
        
    } failure:^(NSError *error) {
        
    }];
    
}

- (void)BulletData {
    [JQAFNetTool GETNetWithUrl:@"http://pudding.cc/api/v1/ep/570870aee397fa903c8b46b0/bullet/?offset=0&limit=500&apiKey=yuki_android&deviceKey=ffffffff-aecb-dcd6-ffff-ffffeb6b6ed7&version=2.8.9&brand=samsung&model=SM-G906S&osv=4.4.2&os=Android&cpuArch=armv7l&timestamp=1460619673&channelId=Wandoujia&auth1=09bc2f5fa8683db810578bceb61ca7dc&currentUserId=570af1c0e397fa4e1d8b4854&auth2=4294855a2797bc51e79029daf6c1c620" body:nil headerFile:nil response:JQJSON success:^(id result) {
        if (result) {
            NSMutableArray *array = [NSMutableArray arrayWithArray:result];
            self.bulletSource = [NSMutableArray arrayWithCapacity:0];
            for (NSDictionary *dic in array) {
                WD_BulletModel *bulletModel = [[WD_BulletModel alloc] initWithDataSource:dic];
                [bulletModel setValuesForKeysWithDictionary:dic];
                [self.bulletSource addObject:bulletModel.content];
            }
            self.bullerManager = [[WD_BulletManager alloc] init];
            __weak WD_HomeDetailViewController *homeVC = self;
            self.bullerManager.FireBulletBlock = ^(WD_BulletView *kBulletView){
                [homeVC addkBulletView:kBulletView];
            };
            self.bullerManager.bulletArr = [NSMutableArray arrayWithArray:self.bulletSource];
            
            self.videoId = [[NSString alloc] init];
            NSLog(@"%@", self.bulletSource);
        }
    } failure:^(NSError *error) {
        
    }];
    
}

- (void)addkBulletView:(WD_BulletView *)bulletView {
    bulletView.frame = CGRectMake(CGRectGetWidth(self.view.frame)+50, 50 + 30 * bulletView.trajectory, CGRectGetWidth(bulletView.bounds), CGRectGetHeight(bulletView.bounds));
    [self.play addSubview:bulletView];
    [bulletView startFire];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return 40;
        } else {
            return 60;
        }
    }
    return 100;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 2;
    } else if (section == 2) {
        return 1;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            WD_HomeDetailMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"message"];
            cell.movieModel = self.movieModel;
            self.vedioName = self.movieModel.title;
            return cell;
        } else if (indexPath.row == 1) {
            WD_HomeMessageDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"messageDetail"];
            cell.movieModel = self.movieModel;
            return cell;
        }
    } else if (indexPath.section == 1) {
        WD_HomeDetailDownLoadCell *cell = [tableView dequeueReusableCellWithIdentifier:@"down"];
        cell.downLoadBlock = ^{
            [self downLoadBut];
        };
        return cell;
    } else if (indexPath.section == 2) {
        WD_HomeDetailUserCell *cell = [tableView dequeueReusableCellWithIdentifier:@"user"];
        if (self.movieModel.users) {
            WD_MovieUserModel *userModel = self.movieModel.users;
            cell.user = userModel;
        }
        return cell;
    }
    if (indexPath.section == 3) {
        WD_HomeDetailTopicCell *cell = [tableView dequeueReusableCellWithIdentifier:@"topic"];
        return cell;
    }
    
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return self.sectionArr[section];
}

- (void)downLoadBut{
    
    //    self.downloadlable.text = @"已经添加下载";
    //    [self.view addSubview:self.downloadlable];
    //    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    //
    //        self.downloadlable.hidden = YES;
    //
    //    });
    //    [self.downloadButton setBackgroundImage:[UIImage imageNamed:@"downOK"] forState:UIControlStateNormal];
    //
    //    self.isDown = YES;
    
    
    NSURL *url = [NSURL URLWithString:self.url];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
    
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionDownloadTask *downLoad = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if (error) {
            NSLog(@"error = %@", error.localizedDescription);
        } else {
            //            NSLog(@"%@", location);
        }
        
        // 如果要保存文件,需要将文件保存至沙盒
        // 1. 根据URL获取到下载的文件名
        NSString *fileName = [self.vedioName lastPathComponent];
        // 2. 生成沙盒的路径
        NSArray *docs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        
        NSString *path = [docs[0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp4", fileName]];
        
        NSLog(@"路径  %@", path);
        
        
        NSURL *toURL = [NSURL fileURLWithPath:path];
        
        
        
        // 3. 将文件从临时文件夹复制到沙盒,在iOS中所有的文件操作都是使用NSFileManager
        
        [[NSFileManager defaultManager] copyItemAtURL:location toURL:toURL error:nil];
        
        
        // 4. 显示下载完成lable
        dispatch_async(dispatch_get_main_queue(), ^{
            
            
            //            self.downloadlable.text = @"下载成功";
            //            [self.view addSubview:self.downloadlable];
            //            [self.downloadButton setBackgroundImage:[UIImage imageNamed:@"downOK"] forState:UIControlStateNormal];
            
            
            //延时之行一段代码
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                //                self.downloadlable.hidden = YES;
                
                
                
            });
            
        });
        //        self.isDown = YES;
        
    }];
    
    //4.因为任务默认是挂起状态，需要恢复任务（执行任务）
    [downLoad resume];
    
    
}

- (void)getData {
    
    NSArray  *paths  =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    
    NSString *docDir = [paths objectAtIndex:0];
    
    NSFileManager* fm=[NSFileManager defaultManager];
    
    NSArray *files = [fm subpathsAtPath:docDir];
    //    NSLog(@" 55    %@    ",files);
    
    self.strNameArray = [NSMutableArray arrayWithCapacity:0];
    
    for (NSString *str in files) {
        if ([str hasSuffix:@".mp4"]) {
            
            NSString *string = [str substringToIndex:str.length - 4];
            
            [self.strNameArray addObject:string];
        }
    }
}

// 切换高清按钮
- (void)changeUrlButtonAction:(UIButton *)sender {
    
    sender.selected = !sender.selected;
    if (sender.selected) {
        self.play.url = self.url;
        NSLog(@"标清：%@", self.url);
    } else {
        self.play.url = self.viviUrl;
        NSLog(@"高清：%@", self.viviUrl);
        
    }
}

- (void)bulletButtonAction:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        [self.bullerManager start];
    } else {
        [self.bullerManager stop];
    }
}

// iOS 9 改变状态栏
- (UIStatusBarStyle)preferredStatusBarStyle
{
    
    return UIStatusBarStyleLightContent;
    
}

- (void)bigBlock {
    //    self.tableView.hidden = YES;
}
- (void)smallBlock {
    self.tableView.hidden = NO;
}
- (void)backBlock {
    [self.navigationController popViewControllerAnimated:YES];
    [self.play.player pause];
    self.backRootBlock(self.url);
    self.navigationController.navigationBarHidden = NO;
    self.tabBarController.tabBar.hidden = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
